// 处理属性
function getProps (attrs) {
  let str = '';
  for (let i = 0; i < attrs.length; i ++) {
    let attr = attrs[i];
    // 处理行内样式
    if (attr.name == 'style') {
      let obj = {};
      attr.value.split(';').forEach(item => {
        let [key, val] = item.split(':');
        obj[key] = val;
      });
      attr.value = obj;
    }

    str += `${attr.name}:${JSON.stringify(attr.value)},`
  }

  return `{${str.slice(0, -1)}}`;
}

// 处理元素的子节点
function genChildren(el) {
  let children = el.children;
  if (children) {
    return children.map(child => gen(child)).join(',')
  }
}

// 匹配模版语法{{}}
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g
function gen (node) {
  if (node.type === 1) {
    // 元素
    return generate(node)
  } else {
    // 文本
    // 1、只是纯文本，没有差值表达式
    ///2、有{{}}
    let text = node.text;
    if (!defaultTagRE.test(text)) {
      return `_v(${JSON.stringify(text)})`;
    }

    // 解析 {{}} 表达式
    let tokens = [];
    let lastIndex = defaultTagRE.lastIndex = 0
    let match;
    while (match = defaultTagRE.exec(text)) {
      let index = match.index;
      if (index > lastIndex) {
        tokens.push(JSON.stringify(text.slice(lastIndex, index)));
      }

      tokens.push(`_s(${match[1].trim()})`);
      lastIndex = index + match[0].length;
    }

    if (lastIndex < text.length) {
      tokens.push(JSON.stringify(text.slice(lastIndex)));
    }
    return `_v(${tokens.join('+')})`;
  }
}


export function generate (el) {
  // console.log('el==', el);
  let children = genChildren(el)
  // AST语法树先到字符串，再到render函数
  let code = `_c('${el.tag}',${el.attrs && el.attrs.length ? `${getProps(el.attrs)}` : `null`},${children ? `${children}` : `null`})`;
  return code;
}